import {
  ActionType,
  ProColumns,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Form, Input, InputNumber, message } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/insuredPerson';
import servicesItem from '@/services/insuredPersonItem';
import MaterialWin from './components/material';
import React from 'react';


const { queryList, addData, modifyData, deleteData } = services.InsuredPersonController
const { queryList: queryItem } = servicesItem.InsuredPersonItemController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.InsuredPerson) => {
  const hide = message.loading('正在操作');
  try {
    id ? await modifyData({ id }, { ...fields }) : await addData({ ...fields });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.InsuredPerson[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deleteData({
      id: selectedRows.find((row) => row.id)?.id || '',
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const InsuredPersonList = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 1200 })
  const [materialProps, setMaterialProps] = useState<any>({ modalVisible: false, title: '物料信息', id: null, width: 1000 })
  const [approveProps, setApproveProps] = useState<any>({ modalVisible: false, title: '审批信息', id: null, width: 1000 })
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<API.InsuredPerson[]>([]);
  const columns: ProColumns<API.InsuredPerson>[] = [
    {
      title: '姓名', dataIndex: 'name', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '性别', dataIndex: 'gender', width: 100, ellipsis: true, valueType: 'radio', valueEnum: { '男': '男', '女': '女' },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '个人编号', dataIndex: 'personalNumber', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '身份证号', dataIndex: 'idCardNumber', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '当前参保状态', dataIndex: 'insuranceStatus', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '实缴月份', dataIndex: 'paidMonths', width: 150, ellipsis: true, valueType: 'digit',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '现参保单位', dataIndex: 'currentInsuranceUnit', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '参保起止日期', dataIndex: 'insurancePeriod', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
      renderFormItem: () => {
        return <Input placeholder='如2021年12月至--、2021年12月至2023年9月' />
      },
    },
    {
      title: '参保单位', dataIndex: 'insuranceUnit', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '经办机构', dataIndex: 'handlingAgency', width: 150, ellipsis: true, valueEnum: {
        '昆明市盘龙区社会保险局': '昆明市盘龙区社会保险局',
        '昆明市五华区社会保险局': '昆明市五华区社会保险局',
        '昆明市西山区社会保险局': '昆明市西山区社会保险局',
        '昆明市官渡区社会保险局': '昆明市官渡区社会保险局',
        '昆明市呈贡区社会保险局': '昆明市呈贡区社会保险局',
        '昆明市东川区社会保险局': '昆明市东川区社会保险局',
        '昆明市晋宁区社会保险局': '昆明市晋宁区社会保险局'
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '险种', dataIndex: 'insuranceType', width: 150, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record: any) => (
        <>
          <a
            onClick={() => {
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 1200 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            setMaterialProps({ ...materialProps, modalVisible: true, title: '参保记录', id: record.id, record, width: 1000 })
          }}>参保记录</a>
          <Divider type="vertical" />
          <a onClick={async () => {
            const { total } = await queryItem({
              current: 1,
              pageSize: 20,
              insuredPersonId: record.id
            });
            if (total == 0) return message.error('请先添加社保记录')
            window.open("/social_new.html?id=" + record.id, "_blank");
          }}>导出预览</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '社保证明',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 1800 }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowProps({ ...winProps, title: '新建', id: null, record: { insuranceStatus: '正常参保', insuranceType: '城镇职工基本养老保险' }, width: 1200 })
              handleModalVisible(true)
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { data, success, total } = await queryList({
            ...params,
          });

          return {
            data: data || [],
            success,
            total
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.InsuredPerson, API.InsuredPerson>
          onSubmit={async (value) => {
            const success = await handleAdd(winProps.id, value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            layout: 'inline',
            labelCol: { style: { width: 180, margin: 4 } },
            wrapperCol: { style: { margin: 4, minWidth: 300 }, span: 16 },
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => {
          setMaterialProps({})
        }}
        {...materialProps}
      >
        <MaterialWin id={materialProps.id} />
      </CreateForm>
    </PageContainer>

  );
}

export default InsuredPersonList;